/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JDialogTesterPreLoadJar.java
 *
 * Created on 11/05/2013, 08:49:22 PM
 */
package com.ufps.cuatro.vistas;

import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.Timer;

import org.jdesktop.application.Action;

import com.ufps.cuatro.controlador.render.UtilRender;
import com.ufps.cuatro.modelo.analizador.CargadorClases;
import com.ufps.cuatro.modelo.analizador.UtilAnalizador;
import com.ufps.cuatro.util.Utileria;
import com.ufps.cuatro.util.generadores.TesterLoadJar;
import com.ufps.cuatro.util.opciones.MyPreferences;
import com.ufps.cuatro.util.opciones.UtilOpciones;

/**
 *
 * @author CARLOSALBERTO
 */
public class JDialogTesterPreLoadJar extends javax.swing.JDialog {
    private static final long serialVersionUID = 8352166627220342493L;    
       
    private Timer timer;
    private TesterLoadJar task;    
    private String newline;   
    private ArrayList<File> objJarExtern;

    /** Creates new form JDialogTesterPreLoadJar */
    public JDialogTesterPreLoadJar(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();        
        this.setIconImage(Utileria.leerIconoAppEnImagen(Utileria.MODO_16x16).getImage());
        jButtonOk.setEnabled(false);
        
        objJarExtern = new ArrayList<File>();
        
        newline = System.getProperty("line.separator");

        task = new TesterLoadJar(Utileria.objFileJar);        
        
        jProgressBarTesterLoadJar.setMinimum(0);
        jProgressBarTesterLoadJar.setMaximum((int)Utileria.objFileJar.length());
        jProgressBarTesterLoadJar.setValue(0);
        jProgressBarTesterLoadJar.setStringPainted(true);
        
        jEditorPaneTesterLoadJar.setContentType("text/html"); 
        jEditorPaneTesterLoadJar.setMargin(new Insets(5,5,5,5));
        jEditorPaneTesterLoadJar.setEditable(false);       

        //create a timer
        timer = new Timer(TesterLoadJar.FRECUENCE_TIMER, new TimerListener());
        timer.start();
        task.go();        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel4 = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jProgressBarTesterLoadJar = new javax.swing.JProgressBar();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListTesterLoadJar = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        jEditorPaneTesterLoadJar = new javax.swing.JEditorPane();
        jToolBar2 = new javax.swing.JToolBar();
        jButtonOk = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Preanalisis del Jar");
        setResizable(false);

        jLabel4.setBackground(new java.awt.Color(255, 255, 255));
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(JDialogTesterPreLoadJar.class);
        jLabel4.setIcon(resourceMap.getIcon("jLabel4.icon")); // NOI18N
        jLabel4.setText("<html><b>Preanalisis del Jar Seleccionado.</b><br> <p> Espere mientras se analizan las referencias externas del Jar seleccionado, al terminar el analisis si existen, clases sin referencias debe suministrar los jar que las contienen.</p></html>");
        jLabel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel4.setName("jLabel4"); // NOI18N
        jLabel4.setOpaque(true);

        jToolBar1.setFloatable(false);
        jToolBar1.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jToolBar1.setRollover(true);
        jToolBar1.setBorderPainted(false);
        jToolBar1.setName("jToolBar1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(JDialogTesterPreLoadJar.class, this);
        jButton1.setAction(actionMap.get("addJar")); // NOI18N
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setName("jButton1"); // NOI18N
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton1);

        jSeparator2.setName("jSeparator2"); // NOI18N
        jToolBar1.add(jSeparator2);

        jButton2.setAction(actionMap.get("delJar")); // NOI18N
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setName("jButton2"); // NOI18N
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton2);

        jLabel1.setText("<html>Ingrese los Jar externos que contienen las clases que no pasaron la prueba (Color <b><font color = #990000>Rojo</font></b>).</html>");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText("Consola de Analisis.");
        jLabel2.setName("jLabel2"); // NOI18N

        jProgressBarTesterLoadJar.setName("jProgressBarTesterLoadJar"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jListTesterLoadJar.setName("jListTesterLoadJar"); // NOI18N
        jScrollPane1.setViewportView(jListTesterLoadJar);

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jEditorPaneTesterLoadJar.setContentType("text/html"); // NOI18N
        jEditorPaneTesterLoadJar.setEditable(false);
        jEditorPaneTesterLoadJar.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jEditorPaneTesterLoadJar.setText("");
        jEditorPaneTesterLoadJar.setToolTipText("");
        jEditorPaneTesterLoadJar.setName("jEditorPaneTesterLoadJar"); // NOI18N
        jScrollPane3.setViewportView(jEditorPaneTesterLoadJar);

        jToolBar2.setFloatable(false);
        jToolBar2.setName("jToolBar2"); // NOI18N

        jButtonOk.setAction(actionMap.get("ok")); // NOI18N
        jButtonOk.setFocusable(false);
        jButtonOk.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonOk.setName("jButtonOk"); // NOI18N
        jButtonOk.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(jButtonOk);

        jButtonCancel.setAction(actionMap.get("cancel")); // NOI18N
        jButtonCancel.setFocusable(false);
        jButtonCancel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonCancel.setName("jButtonCancel"); // NOI18N
        jButtonCancel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(jButtonCancel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 494, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 494, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 494, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jProgressBarTesterLoadJar, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)))
                .addContainerGap())
            .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jProgressBarTesterLoadJar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JDialogTesterPreLoadJar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JDialogTesterPreLoadJar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JDialogTesterPreLoadJar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JDialogTesterPreLoadJar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                JDialogTesterPreLoadJar dialog = new JDialogTesterPreLoadJar(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    @Action
    public void addJar() {               
        Utileria.strTempDir = UtilOpciones.objPreferences.getString(MyPreferences.FILE_OPEN_JAR);
        File objOutPutFileSelected = UtilAnalizador.getFileOpenSelectedJar();
        if(objOutPutFileSelected != null){ 
            if(objOutPutFileSelected.exists()){                
                Utileria.strTempDir = objOutPutFileSelected.getParent();
                UtilOpciones.objPreferences.addOpcion(MyPreferences.FILE_OPEN_JAR, objOutPutFileSelected.getAbsolutePath());
                objJarExtern.add(objOutPutFileSelected);                
                UtilRender.helperJList(jListTesterLoadJar, objJarExtern,ListSelectionModel.SINGLE_SELECTION);                
            }            
        }        
    }

    @Action
    public void delJar() {
        if(this.objJarExtern.isEmpty()){
            Utileria.mostrarMensaje(this, "Debe Agregar Referencias de Jar.", "", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if(this.jListTesterLoadJar.isSelectionEmpty()){
            Utileria.mostrarMensaje(this, "Debe Seleccionar una Referencia.", "", JOptionPane.WARNING_MESSAGE);
            return;
        }
        int i = this.jListTesterLoadJar.getSelectedIndex();        
        File objFile = objJarExtern.get(i);        
        if(!Utileria.confirmarOrden(this, "¿Desea Eliminar la Referencia Seleccionada?", ""))return;                
        if(!objJarExtern.isEmpty()){            
            if(objJarExtern.contains(objFile)){
                if(objJarExtern.remove(objFile)){
                    UtilRender.helperJList(jListTesterLoadJar, objJarExtern,ListSelectionModel.SINGLE_SELECTION);
                }
            }
        }
        
    }
    
    //the actionPerformed method in this class
    //is called each time the Timer "goes off"
    class TimerListener implements ActionListener {
        private String strConsole = "Iniciando Análisis...<br>";
        public void actionPerformed(ActionEvent evt) {
            if(task.getStatMessage() != null){
                jProgressBarTesterLoadJar.setValue((int)task.getCurrent());
                strConsole += task.getStatMessage() + "<br>";
                jEditorPaneTesterLoadJar.setText("<html>" + strConsole  + "</html>");                                
                jEditorPaneTesterLoadJar.setCaretPosition(jEditorPaneTesterLoadJar.getDocument().getLength());
            }
            if (task.done()) {                
                timer.stop();                
                jProgressBarTesterLoadJar.setValue(jProgressBarTesterLoadJar.getMinimum());
                switch(getActionTesterLoadJar()){
                    case TesterLoadJar.PROCESS_OK:
                        UtilRender.msgInformacion("El Analisis del Jar ha finalizado Correctamente.");
                        dispose();
                        break;
                    case TesterLoadJar.PROCESS_ERROR:    
                        UtilRender.msgError("El análisis ha finalizado con Errores de Referencias para poder continuar debe\n"
                                + "agregar al análisis los jar que las contienen. Para identificar cuales son las clases\n"
                                + "revise la Consola de Análisis la cual contendra en color Rojo todas aquellas clases con errores.");
                        jButtonOk.setEnabled(true);
                        break;
                }                
            }            
        }
    }
    
    public int getActionTesterLoadJar(){
        return task.getAction();
    }

    @Action
    public void ok() {
        if(this.objJarExtern.isEmpty()){
            Utileria.mostrarMensaje(this, "Debe Agregar Referencias de Jar.", "", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if(!Utileria.confirmarOrden(this, "¿Desea Cargar los Jar que contienen las Referencias con Errores?\n"
                + "Tenga presente que es responsabilidad del usuario incluir todos los jar que\n"
                + "contienen las referencias externas y el no hacerlo puede causar que no se cargue\n"
                + "adecuadamente el modelo del mundo que representa el jar principal.", "")){
            return;
        }
        if(loadJar()){
            task.setAction(TesterLoadJar.PROCESS_OK);
            dispose();            
        }
        else{
            UtilRender.msgError("Se han Generado Errores al Registrar los Jar que Contienen las Referencias Externas.", this);
        }
    }

    @Action
    public void cancel() {
        if(!Utileria.confirmarOrden(this, "¿Desea Cancelar el Preanalisis?\n"
                + "Tenga presente que no podrá Cargar el Jar Seleccionado.", "")){
            return;
        }
        task.setAction(TesterLoadJar.PROCESS_CANCEL);
        dispose();
    }
    
    private boolean loadJar(){
        try {
            CargadorClases mc = new CargadorClases();
            for(File objFile : objJarExtern){            
                try {
                    mc.addArchivo(objFile);
                } catch (MalformedURLException ex) {
                    Logger.getLogger(JDialogTesterPreLoadJar.class.getName()).log(Level.SEVERE, null, ex);
                    return false;
                }
            }
            return true;
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(JDialogTesterPreLoadJar.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonOk;
    private javax.swing.JEditorPane jEditorPaneTesterLoadJar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JList jListTesterLoadJar;
    private javax.swing.JProgressBar jProgressBarTesterLoadJar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    // End of variables declaration//GEN-END:variables
}
